﻿using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class MouseClick : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IDragHandler
{
    [System.Serializable] public class MouseEvent : UnityEvent { }
    [System.Serializable] public class MouseEventWithData : UnityEvent<PointerEventData> { }

    public MouseEvent onLeftClick = new MouseEvent();
    public MouseEventWithData onLeftClickWithEvent = new MouseEventWithData();

    public MouseEvent onRightClick = new MouseEvent();
    public MouseEventWithData onRightClickWithEvent = new MouseEventWithData();

    public MouseEvent onClick = new MouseEvent();
    public MouseEventWithData onClickWithEvent = new MouseEventWithData();

    [Tooltip("点击的最大允许时间（秒）")]
    public float maxClickTime = 0.5f;

    [Tooltip("点击时允许的最大移动距离（像素）")]
    public float maxMoveDistance = 10f;
    private Vector2 pointerDownPosition;
    private bool isPointerDown = false;
    private float pointerDownTime;
    private PointerEventData currentEventData;
    public void OnPointerDown(PointerEventData eventData)
    {
        isPointerDown = true;
        pointerDownPosition = eventData.position;
        pointerDownTime = Time.unscaledTime;
        currentEventData = eventData;
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        if (!isPointerDown)
            return;
        float timeHeld = Time.unscaledTime - pointerDownTime;
        float distanceMoved = Vector2.Distance(eventData.position, pointerDownPosition);

        bool isClick = timeHeld <= maxClickTime && distanceMoved <= maxMoveDistance;

        if (isClick)
        {
            if (eventData.button == PointerEventData.InputButton.Left)
            {
                onLeftClick.Invoke();
                onLeftClickWithEvent.Invoke(eventData);
            }
            else if (eventData.button == PointerEventData.InputButton.Right)
            {
                onRightClick.Invoke();
                onRightClickWithEvent.Invoke(eventData);
            }

            onClick.Invoke();
            onClickWithEvent.Invoke(eventData);
        }

        isPointerDown = false;
    }

    public void OnDrag(PointerEventData eventData)
    {
        isPointerDown = false;
    }
    public void Add(UnityAction action) => onClick.AddListener(action);
    public void Add(UnityAction<PointerEventData> action) => onClickWithEvent.AddListener(action);

    public void AddLeft(UnityAction action) => onLeftClick.AddListener(action);
    public void AddLeft(UnityAction<PointerEventData> action) => onLeftClickWithEvent.AddListener(action);

    public void AddRight(UnityAction action) => onRightClick.AddListener(action);
    public void AddRight(UnityAction<PointerEventData> action) => onRightClickWithEvent.AddListener(action);
}